package cn.com.ejiakanghu.config;

import cn.com.ejiakanghu.dto.Location;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.net.URLDecoder;

public class LocationInterceptor implements HandlerInterceptor {
    private static final String HEAD_PROVINCE = "province";
    private static final String HEAD_CITY = "city";
    private static final String HEAD_LNG = "lng";
    private static final String HEAD_LAT = "lat";
    private static final String DEFAULT_PROVINCE = "江苏省";
    private static final String DEFAULT_CITY = "苏州市";
    private static final BigDecimal DEFAULT_LNG = BigDecimal.valueOf(120.651849);
    private static final BigDecimal DEFAULT_LAT = BigDecimal.valueOf(31.318871);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String province = request.getHeader(HEAD_PROVINCE);
        String city = request.getHeader(HEAD_CITY);
        String lng = request.getHeader(HEAD_LNG);
        String lat = request.getHeader(HEAD_LAT);
        Location location = new Location();
        location.setProvince(StringUtils.isNotEmpty(province) ? URLDecoder.decode(province, "UTF-8") : DEFAULT_PROVINCE);
        location.setCity(StringUtils.isNotEmpty(city) ? URLDecoder.decode(city, "UTF-8") : DEFAULT_CITY);
        location.setLng(StringUtils.isNotEmpty(lng) ? new BigDecimal(lng) : DEFAULT_LNG);
        location.setLat(StringUtils.isNotEmpty(lat) ? new BigDecimal(lat) : DEFAULT_LAT);
        LocationContext.set(location);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
